package cmd

import (
	"bufio"
	"fmt"
	"gitee/kubehark/kubehark-client/pkg/config"
	"github.com/spf13/cobra"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/clientcmd/api"
	"os"
	"strings"
)

type SetUpCmd struct {
	Name         string
	OidcClientID string
	OidcIssuer   string
	OidcSecret   string
	Server       string
}

func (this *SetUpCmd) SetFlag(command *cobra.Command) {
	command.Flags().StringVarP(&this.Name, "name", "n", "default", "name of context suffix")
	command.Flags().StringVarP(&this.OidcClientID, "oidc-client-id", "o", "", "oidc client id")
	command.Flags().StringVarP(&this.OidcIssuer, "oidc-issuer", "s", "", "oidc issuer")
	command.Flags().StringVarP(&this.Server, "server", "r", "", "server")
	command.Flags().StringVarP(&this.OidcSecret, "oidc-secret", "t", "", "oidc secret")

}

func NewSetUpCmd() *cobra.Command {
	infocmd := &SetUpCmd{}
	var Cmd = &cobra.Command{
		Use:   "setup",
		Short: "初始化",
		Long:  `初始化插件配置`,
		Run: func(cmd *cobra.Command, args []string) {
			var (
				c   *api.Config
				err error
			)
			r := clientcmd.NewDefaultClientConfigLoadingRules()

			kubeConfigFilePath := r.GetDefaultFilename()
			if _, err = os.Stat(kubeConfigFilePath); os.IsNotExist(err) {
				var cf *os.File
				cf, err = os.Create(kubeConfigFilePath)
				if err != nil {
					return
				}
				cf.Close()
			}

			c, err = clientcmd.LoadFromFile(kubeConfigFilePath)
			if err != nil {
				return
			}

			contextName := infocmd.Name
			contextClusterName := infocmd.Name + "-cluster"
			contextAuthInfoName := infocmd.Name + "-user"

			targetContext := &api.Context{
				Cluster:  contextClusterName,
				AuthInfo: contextAuthInfoName,
			}
			var existsContext *api.Context
			existsContext, err = config.GetContext(c, contextName)
			if existsContext != nil {
				reader := bufio.NewReader(os.Stdin)
				fmt.Printf("context %s exists ,should overwrite ? :[Y/N]", existsContext)
				text, _ := reader.ReadString('\n')
				text = strings.ToLower(strings.Trim(text, "\n"))
				if text != "y" {
					os.Exit(0)
				}
				targetContext.Namespace = existsContext.Namespace
			} else {
				if c.Contexts == nil {
					c.Contexts = make(map[string]*api.Context)
				}
			}
			c.CurrentContext = contextName
			c.Contexts[contextName] = targetContext

			c.Clusters[contextClusterName] = &api.Cluster{
				InsecureSkipTLSVerify: true,
				Server:                infocmd.Server,
			}

			c.AuthInfos[contextAuthInfoName] = &api.AuthInfo{
				Exec: &api.ExecConfig{
					APIVersion: "client.authentication.k8s.io/v1beta1",
					Args: []string{
						"refresh-token",
					},
					Command: "kubectl-hark",
					Env: []api.ExecEnvVar{
						{
							Name:  "oidc-client-id",
							Value: infocmd.OidcClientID,
						},
						{
							Name:  "oidc-server",
							Value: infocmd.OidcIssuer,
						},
						{
							Name:  "server",
							Value: infocmd.Server,
						},
						{
							Name:  "oidc-secret",
							Value: infocmd.OidcSecret,
						},
						{
							Name:  "refresh-token",
							Value: "",
						},
					},
					ProvideClusterInfo: false,
				},
			}

			if err = clientcmd.WriteToFile(*c, r.GetDefaultFilename()); err != nil {
				return
			}

			_, _ = fmt.Fprintf(cmd.OutOrStdout(), "setup oidc-issuer %s server %s success", infocmd.OidcIssuer, infocmd.Server)
			return
		},
	}
	infocmd.SetFlag(Cmd)
	return Cmd
}
